<template>
<div>
    <div class="common-form">{{$t('plus.activity_product')}}</div>

    <el-form-item :label="$t('plus.product_management')" prop="tableData" :rules="rulesProduct">
      <el-button icon="Plus" @click="changeProduct(form.tableData)"
        >{{$t('plus.select_product')}}</el-button
      >
      <div class="d-s-c pt16 max-w460 active-all-set">
        <div style="width: 60px">{{$t('plus.batch_setting')}}</div>
        <div class="flex-1">
          <el-input
            v-model="allAssemblePrice"
            type="number"
            min="0"
            :placeholder="$t('plus.group_price')"
          ></el-input>
        </div>
        <div class="flex-1 ml10">
          <el-input
            v-model="allAssembleStock"
            type="number"
            min="0"
            :placeholder="$t('plus.group_inventory')"
          ></el-input>
        </div>
        <div class="flex-1 ml10">
          <el-input
            v-model="allAssembleNum"
            type="number"
            min="0"
            :placeholder="$t('plus.group_people_count')"
          ></el-input>
        </div>
        <div class="flex-1 ml10">
          <el-input
            v-model="allLimitNum"
            type="number"
            min="0"
            :placeholder="$t('plus.purchase_limit_quantity')"
          ></el-input>
        </div>
        <div class="ml10"><el-button @click="allApply">{{$t('plus.apply')}}</el-button></div>
      </div>
      <div class="pt16">
        <el-table
          size="mini"
          :data="form.tableData"
          :span-method="objectSpanMethod"
          border
          style="width: 100%"
        >
          <el-table-column :label="$t('plus.product_name')" width="300">
            <template #default="scope">
              <p class="text-ellipsis-2">{{scope.row.productName}}</p>
            </template>
          </el-table-column>
          <el-table-column :label="$t('plus.specification')" width="180">
            <template #default="scope">
              <div class="gray" v-if="scope.row.specType == 10">{{$t('plus.no_specification')}}</div>
              <div v-if="scope.row.specType == 20">
                <div
                  class="spec-min-box"
                  v-if="scope.row.specName != null && scope.row.specName != ''"
                >
                  <p class="text-ellipsis" :title="scope.row.specName">
                    {{scope.row.specName}}
                  </p>
                  <el-icon @click="deleteClick(scope.$index)"
                    ><Close
                  /></el-icon>
                  <el-icon @click="specsFunc(scope.$index, scope.row, true)"
                    ><CaretRight
                  /></el-icon>
                </div>
                <el-button
                  v-else
                  size="mini"
                  icon="Plus"
                  @click="specsFunc(scope.$index, scope.row)"
                  >{{$t('plus.add_specification')}}</el-button
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="productPrice" :label="$t('plus.price2')"></el-table-column>
          <el-table-column :label="$t('plus.group_price')">
            <template #default="scope">
              <el-input
                size="small"
                :class="{  isvalid: scope.row.priceValid == true}"
                type="number"
                min="0"
                step="0.01"
                v-model="scope.row.assemblePrice"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column :label="$t('plus.group_inventory')">
            <template #default="scope">
              <el-input
                size="small"
                :class="{  isvalid: scope.row.stockValid == true}"
                type="number"
                min="0"
                v-model="scope.row.assembleStock"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="salesNum" :label="$t('plus.sold')"></el-table-column>
          <el-table-column :label="$t('plus.group_people_count')">
            <template #default="scope">
              <el-input
                size="small"
                :class="{  isvalid: scope.row.assembleNumValid == true}"
                type="number"
                min="0"
                v-model="scope.row.assembleNum"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column :label="$t('plus.purchase_limit_quantity')">
            <template #default="scope">
              <el-input
                size="small"
                :class="{  isvalid: scope.row.limitNumValid == true}"
                type="number"
                min="1"
                v-model="scope.row.limitNum"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column :label="$t('plus.virtual_sales')">
            <template #default="scope">
              <el-input
                size="small"
                :class="{  isvalid: scope.row.sortValid == true}"
                type="number"
                min="0"
                v-model="scope.row.salesInitial"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column :label="$t('plus.sort')">
            <template #default="scope">
              <el-input
                size="small"
                :class="{  isvalid: scope.row.sortValid == true}"
                type="number"
                min="0"
                v-model="scope.row.sort"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            :label="$t('plus.action')"
            :width="type == 'edit' ? 90 : 60"
          >
            <template #default="scope">
              <el-button
                v-if="type == 'edit'"
                @click="showFunc(scope.$index, scope.row)"
                type="text"
                size="small"
                >{{scope.row.isDelete == 0 ? $t("plus.hide") : $t("plus.show")}}</el-button
              >
              <el-button
                @click="deleteClick(scope.$index, true)"
                type="text"
                size="small"
                >{{$t('plus.delete')}}</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form-item>

    <!--商品选择-->
    <Product
      :isProduct="isProduct"
      :excludeIds="excludeIds"
      :islist="true"
      @closeDialog="closeDialogFunc"
    ></Product>

    <!--规格选择-->
    <Specs
      :isspecs="isspecs"
      :productId="curProduct.productId"
      :excludeIds="SpecExcludeIds"
      :islist="true"
      @close="closeSpecs"
    ></Specs>
  </div>
</template>

<script>
import PorductApi from "@/api/product.js";
import Product from "@/components/product/Product.vue";
import Specs from "@/components/product/Specs.vue";
import { mergeTable } from "@/utils/table.js";
export default {
  components: {
    /*选择商品组件*/
    Product,
    /*选择规格*/
    Specs
  },
  data() {
    /*验证名称*/
    const validatorProduct = (rule, value, callback) => {
      if (value.length < 1) {
        return callback(new Error($t("plus.select_product2")));
      } else {
        let flag = false;
        for (let i = 0; i < this.form.tableData.length; i++) {
          let item = this.form.tableData[i];
          if (!flag) {
            let reg = item.assemblePrice == "" || item.assembleStock == "" || item.limitNum == "" || item.sort == "";
            let reg2 = parseFloat(item.assemblePrice) == 0 || parseInt(item.assembleStock) < 1 || parseInt(item.limitNum) < 1;
            if (reg || reg2) {
              flag = true;
            }
          }
          if (parseInt(item.assembleStock) > 0) {
            item.stockValid = true;
          } else {
            item.stockValid = false;
          }
          if (parseInt(item.assemblePrice) > 0) {
            item.priceValid = true;
          } else {
            item.priceValid = false;
          }
          if (parseInt(item.limitNum) > 0) {
            item.limitNumValid = true;
          } else {
            item.limitNumValid = false;
          }
          if (parseInt(item.sort) > 0) {
            item.sortValid = true;
          } else {
            item.sortValid = false;
          }
          this.form.tableData[i] = item;
        }
        if (flag) {
          return callback(new Error($t("plus.input_valid_info")));
        } else {
          callback();
        }
      }
    };
    return {
      /*是否打开选择商品*/
      isProduct: false,
      /*产品去重*/
      excludeIds: [],
      /*是否打开规格选择*/
      isspecs: false,
      /*查询规格当前商品*/
      curProduct: {},
      /*当前的角标索引*/
      curIndex: -1,
      /*选择规格*/
      specType: false,
      /*规格去重*/
      SpecExcludeIds: [],
      /*批量拼团价*/
      allAssemblePrice: null,
      /*批量拼团库存*/
      allAssembleStock: null,
      /*批量限购*/
      allLimitNum: null,
      /*开团人数*/
      allAssembleNum: null,
      /*验证商品*/
      rulesProduct: [{
        validator: validatorProduct,
        required: true,
        trigger: "blur"
      }]
    };
  },
  props: {
    form: Object,
    type: String
  },
  created() {},
  methods: {
    /*打开添加*/
    changeProduct(list) {
      let arr = [];
      list.forEach(item => {
        arr.push(item.productId);
      });
      this.excludeIds = arr;
      this.isProduct = true;
    },
    /*关闭弹窗*/
    closeDialogFunc(e) {
      let self = this;
      self.isProduct = false;
      if (e.type == "success") {
        let arr = [];
        for (let i = 0; i < e.params.length; i++) {
          let item = e.params[i];
          let obj = {
            productName: item.productName,
            productId: item.productId,
            productPrice: item.productPrice,
            stockNum: item.productStock,
            productSkuId: item.sku != null ? item.sku[0].productSkuId : 0,
            salesNum: 0,
            specType: item.specType,
            assemblePrice: null,
            assembleStock: 0,
            limitNum: 1,
            sort: 100,
            tempProduct: true,
            isDelete: 0,
            assembleNum: 0,
            assembleProductId: 0,
            assembleProductSkuId: 0,
            salesInitial: 0
          };
          arr.push(obj);
        }
        self.form.tableData = self.form.tableData.concat(arr);
        self.form.tableData = mergeTable(this.form.tableData);
      }
    },
    /*打开规格*/
    specsFunc(i, e, type) {
      this.curProduct = e;
      this.curIndex = i;
      let arr = [];
      if (type) {
        this.specType = true;
        this.form.tableData.forEach(item => {
          if (this.curProduct.productId == item.productId) {
            arr.push(item.productSkuId);
          }
        });
      } else {
        this.specType = false;
      }
      this.SpecExcludeIds = arr;
      this.isspecs = true;
    },
    /*关闭规格*/
    closeSpecs(e) {
      this.isspecs = false;
      if (e.type == "success") {
        let arr = [];
        for (let i = 0; i < e.params.length; i++) {
          let item = e.params[i];
          let obj = {
            productName: this.curProduct.productName,
            productId: this.curProduct.productId,
            productPrice: item.specForm.productPrice,
            specType: this.curProduct.specType,
            //productSkuId: this.curProduct.productSkuId,
            assembleProductId: this.curProduct.assembleProductId,
            stockNum: item.productStock,
            salesNum: 0,
            specName: item.specName,
            productSkuId: item.productSkuId,
            assemblePrice: null,
            assembleStock: 0,
            limitNum: 1,
            sort: 100,
            tempProduct: true,
            isDelete: 0,
            assembleNum: 0,
            assembleProductSkuId: 0,
            salesInitial: 0
          };
          arr.push(obj);
        }
        let params = [this.curIndex, this.specType ? 0 : 1].concat(arr);
        this.form.tableData.splice(...params);
        this.form.tableData = mergeTable(this.form.tableData);
      }
    },
    /*删除*/
    deleteClick(e, isType) {
      let curItem = this.form.tableData[e];
      if (curItem.joinNum > 0) {
        ElMessage({
          message: $t("plus.cannot_delete_with_participants"),
          type: "warning"
        });
        return;
      }
      if (isType) {
        /*判断能删除产品*/
        for (let i = 0; i < this.form.tableData.length; i++) {
          let item = this.form.tableData[i];
          if (curItem.productId == item.productId) {
            if (item.salesNum > 0) {
              ElMessage({
                message: $t("plus.sold_product_cannot_delete"),
                type: "warning"
              });
              return;
            }
          }
        }
        for (let i = 0; i < this.form.tableData.length; i++) {
          let item = this.form.tableData[i];
          if (curItem.productId == item.productId) {
            if (this.type == "edit" && e.tempProduct != true) {
              let assembleProductId = item.assembleProductId;
              this.form.productDelIds.push(assembleProductId);
            }
            this.form.tableData.splice(i, 1);
            i--;
          }
        }
      } else {
        /*删除规格*/
        if (parseInt(e.salesNum) > 0) {
          ElMessage({
            message: $t("plus.sold_spec_cannot_delete"),
            type: "warning"
          });
          return;
        }
        let count = 0;
        for (let i = 0; i < this.form.tableData.length; i++) {
          let item = this.form.tableData[i];
          if (curItem.productId == item.productId) {
            count++;
            if (count > 1) {
              break;
            }
          }
        }
        if (count > 1) {
          this.form.tableData.splice(e, 1);
        } else {
          curItem.specName = null;
        }
      }
      this.form.tableData = mergeTable(this.form.tableData);
    },
    /*表格合并行*/
    objectSpanMethod({
      row,
      column,
      rowIndex,
      columnIndex
    }) {
      if (columnIndex === 0 || columnIndex === 6 || columnIndex === 7 || columnIndex === 8 || columnIndex === 9 || columnIndex === 10) {
        if (row.rowSpan != null) {
          return {
            rowspan: row.rowSpan,
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },
    /*全部应用*/
    allApply() {
      let arr = [];
      for (let i = 0; i < this.form.tableData.length; i++) {
        let item = this.form.tableData[i];
        if (item.assemblePrice == null) {
          if (parseInt(this.allAssemblePrice) > parseInt(item.productPrice)) {
            item.assemblePrice = item.productPrice;
          } else {
            item.assemblePrice = this.allAssemblePrice;
          }
        }
        item.assembleStock = item.assembleStock <= 1 ? this.allAssembleStock : item.assembleStock;
        item.limitNum = item.limitNum <= 1 ? this.allLimitNum : item.limitNum;
        item.assembleNum = item.assembleNum <= 1 ? this.allAssembleNum : item.assembleNum;
      }
    },
    /*显示隐藏*/
    showFunc(i, e) {
      if (e.isDelete === 0) {
        e.isDelete = 1;
      } else {
        e.isDelete = 0;
      }
    }
  }
};
</script>

<style lang="scss">
.spec-min-box > i {
  position: absolute;
  right: 0;
  font-size: 16px;
  cursor: pointer;
}
.spec-min-box .el-icon-close {
  top: 0;
  color: red;
  visibility: hidden;
}
td:hover .spec-min-box .el-icon-close {
  visibility: visible;
}
.spec-min-box .el-icon-caret-right {
  bottom: 0;
  transform: rotate(45deg);
  color: #3a8ee6;
}
.el-form-item.is-error .active-all-set .el-input__inner,
.el-form-item.is-error .isvalid .el-input__inner {
  border-color: #c0c4cc;
}
</style>

